package controller.compare;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dbsync4j.core.behavior.Schema;
import dbsync4j.mapper.behavior.compare.DBSyncCompareManager;
import dbsync4j.mapper.behavior.compare.DifferenceCompare;
import dbsync4j.mapper.concrete.compare.ConcreteDBSyncCompareManager;

public class CompareDatabase extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		Schema schemaOrigem = (Schema)req.getSession(false).getAttribute("schemaOrigem");
		Schema schemaDestino = (Schema)req.getSession(false).getAttribute("schemaDestino");
		String view = req.getParameter("view");

		String dispatcher = "/jsp/compare.jsp";

		if(view == null) {
			if(schemaOrigem != null && schemaDestino != null) {

				DBSyncCompareManager compare = new ConcreteDBSyncCompareManager();
				Collection<DifferenceCompare> compareDifferences = compare.compareFullSchema(schemaOrigem, schemaDestino);
				DifferenceCompare[] results = new DifferenceCompare[compareDifferences.size()];

				int aux = 0;
				for(DifferenceCompare dc : compareDifferences) {
					dc.diff();
					results[aux++] = dc;
				}

				req.setAttribute("differenceCompare", results);
				req.setAttribute("comparationTime", compare.comparationTime());

				req.getSession(false).setAttribute("resultadoComparacao", results);			
			}
		} else if(view.equals("2")) {
			if(schemaOrigem != null && schemaDestino != null) {
				DBSyncCompareManager compare = new ConcreteDBSyncCompareManager();
				Collection<DifferenceCompare> compareDifferences = compare.compareFullSchema(schemaOrigem, schemaDestino);

				for(DifferenceCompare dc : compareDifferences) {
					dc.diff();
				}

				req.setAttribute("comparadores", compareDifferences);
				dispatcher = "/jsp/comparedetailgraphics.jsp";
			} else {
				dispatcher = "/jsp/compare.jsp";
			}
		}

		RequestDispatcher requestDispatcher = req.getRequestDispatcher(dispatcher);
		requestDispatcher.forward(req, resp);
	}

}
